/**
 * 
 */
package abel.wlmr.client;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import abel.wlmr.config.MeterStation;
import abel.wlmr.config.MsaConfigLoader;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author Abel
 *
 */
public class WlmrClient {
    private static final Logger log = LoggerFactory.getLogger(WlmrClient.class);

    private static final String STATION_JSON = "config/hat.json";

    private static final int DEFAULT_WLMR_PORT = 7771;

    /**
     * @param args
     * @throws InterruptedException
     * @throws IOException
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        new WlmrClient().run(args);
    }

    private void run(String... args) throws IOException, InterruptedException {
        // check config
        MsaConfigLoader.checkStationFile(STATION_JSON);
        MeterStation station = MsaConfigLoader.getStationMap().values().iterator().next();
        log.info("my station: {}", station);

        int port = DEFAULT_WLMR_PORT;
        String host = "127.0.0.1";

        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        }
        if (args.length > 1) {
            host = args[1];
        }

        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap()
                .group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.SO_KEEPALIVE, true)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(
                            new IdleStateHandler(5, 6, 7),
                            new WlmrPacketEncoder(),
                            new WlmrPacketDecoder(),
                            new WlmrClientHandler());
                    }
                });

            ChannelFuture f = b.connect(host, port).sync();

            log.info("Client connection, about to login...");

            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }
}
